package com.zueb.util;

import com.zueb.pojo.Admin;
import com.zueb.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionUtils {
    static String message = "";

    /**
     * 判断登录用户是否为空
     * @param object
     * @return
     */
    public static boolean isSessionNull(Object object){
        boolean flag;
        if (object != null){
            flag = true;
        }else{
            flag = false;
        }
        return flag;
    }

    /**
     * 判断管理员是否登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public static void isUserSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取Session
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        boolean flag;
        flag = SessionUtils.isSessionNull(loginUser);
        if (!flag) {
            response.sendRedirect("login.jsp");
//            message = "<script>alert('您暂未登录！请登录');window.open('login.jsp','_self')</script>";
//            //把信息放入页面
//            request.setAttribute("message", message);
//            //跳转页面
//            request.getRequestDispatcher("message.jsp").forward(request, response);
        }
    }

    /**
     * 判断管理员是否登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public static void isSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取Session
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        boolean flag = SessionUtils.isSessionNull(admin);
        if (!flag) {
            response.sendRedirect("login.jsp");
            //return;
//            message = "<script>alert('您暂未登录！请登录');window.open('login.jsp','_self')</script>";
//            //把信息放入页面
//            request.setAttribute("message", message);
//            //跳转页面
//            request.getRequestDispatcher("message.jsp").forward(request, response);
        }
    }
}
